package cn.cai.pethome.system.service.impl;

import cn.cai.pethome.base.util.AjaxResult;
import cn.cai.pethome.system.domain.Permission;
import cn.cai.pethome.system.domain.Role;
import cn.cai.pethome.system.mapper.RoleMapper;
import cn.cai.pethome.system.service.IRoleService;
import cn.cai.pethome.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaocai
 * @since 2022-09-05
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Transactional
    @Override
    public void add(Role role) {
        //1.添加t_role表的数据  返回主键
        super.add(role);
        //2.批量添加角色权限中间表数据 t_role_permission
        if (role.getPermissionIds() != null || role.getPermissionIds().size() > 0){

            roleMapper.saveRolePermissionBatch(role.getId(),role.getPermissionIds());
        }

    }

    @Transactional
    @Override
    public void update(Role role) {
        super.update(role);
        //1.如果是修改 先根据角色id清空角色权限中间表的数据
        roleMapper.deleteRolePermissionByRoleId(role.getId());
        //删除了之后再批量添加角色权限中间表数据
        if (role.getPermissionIds() != null || role.getPermissionIds().size() > 0){

            roleMapper.saveRolePermissionBatch(role.getId(),role.getPermissionIds());
        }
    }

    /**
     * 前端返回的权限ids组装成树形结构(二维数组)
     * @param permissionIds
     * @return
     */
    @Override
    public List<List<Long>> getPermissionTreeByRoleid(List<Long> permissionIds) {

        if (permissionIds == null || permissionIds.size() == 0){
            return null;
        }

        List<Permission> permissions = roleMapper.selectBatchIds(permissionIds);

        List<List<Long>> lists = new ArrayList<>();
        for (Permission permission : permissions) {
            //获取它的父亲id
            List<Long> innerList = new ArrayList<>();

            innerList.add(permission.getParent_id());
            innerList.add(permission.getId());
            //将小集合添加到大集合
            lists.add(innerList);
        }
        return lists;

    }
}
